//$URL: http://dasding.googlecode.com/svn/trunk/api/src/main/java/de/piratech/dasding/api/rest/EventResource.java $
//$Id: EventResource.java 139 2013-05-10 22:42:21Z amuthmann@googlemail.com $
/*
 * Copyright 2012 Piratech.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.piratech.dasding.api.rest;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.ws.rs.DefaultValue;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import de.piratech.dasding.data.Event;
import de.piratech.dasding.data.EventCategory;
import de.piratech.dasding.data.User;
import de.piratech.dasding.data.database.DatabaseException;
import de.piratech.dasding.security.annotations.RequireUserRole;
import de.piratech.dasding.services.Geocoder;
import de.piratech.dasding.services.LocationFilter;

/**
 * Resource for public event requests
 * <p>
 * Those include:
 * <p>
 * GET: load a specific event<br>
 * PUT: -<br>
 * POST: -<br>
 * DELETE: -<br>
 * <p>
 * /events/find:
 * <p>
 * GET: fidn a events<br>
 * PUT: -<br>
 * POST: -<br>
 * DELETE: -<br>
 * <p>
 * /events/categories:
 * <p>
 * GET: load all event-categories<br>
 * PUT: -<br>
 * POST: -<br>
 * DELETE: -<br>
 * 
 * @author deveth0
 */
@Path("/events")
@Component
public class EventResource extends AbstractResource {

  private static final Logger LOG = LoggerFactory
      .getLogger(EventResource.class);

  @Autowired
  private LocationFilter locationFilter;

  @Autowired
  private Geocoder geocoder;

  /**
   * Returns all events with the given parameters
   * 
   * http://localhost:8080/dasding.api/api/events/find?lat=10.31&lon=52.123
   * 
   * http://localhost:8080/dasding.api/api/events/find?lat=10.21&lon=52.123&
   * distance=2.3
   * 
   * GET
   * 
   * @param pLatitude
   * @param pLongitude
   * @param pDistance
   *          (default: 5)
   * @param pCategory
   * @return
   */
  @GET
  @Path("/find")
  @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
  public List<Event> findEvents(
      @QueryParam(value = "lat") Float pLatitude,
      @QueryParam(value = "lon") Float pLongitude,
      @DefaultValue(value = "5") @QueryParam(value = "distance") Float pDistance,
      @QueryParam(value = "category") List<String> pCategory) {
    LOG.debug("findEvents(lat={}, lon={}, distance={}, category={})",
        pLatitude, pLongitude, pDistance, pCategory);

    try {
      List<Event> findByCategories = null;
      if (pCategory != null && pCategory.size() > 0) {
        findByCategories = getEventData().findByCategories(pCategory);
      } else {
        findByCategories = getEventData().getEvents();
      }

      if (pLatitude != null && pLongitude != null) {
        if (pDistance <= 0)
          throw getBadRequestException("distance cannot be less than or equal 0");
        List<Event> eventsInArea = locationFilter.getEventsInArea(
            findByCategories, pLatitude, pLongitude, pDistance);
        return eventsInArea == null ? new ArrayList<Event>() : eventsInArea;
      } else {
        return findByCategories;
      }
    } catch (DatabaseException dbe) {
      throw getBadRequestException(dbe);
    }
  }

  /**
   * Creates a new event
   * 
   * http://localhost:8080/dasding.api/api/events
   * 
   * POST
   * 
   * @param pName
   *          (required)
   * @param pDescription
   *          (required)
   * @param pCategoryID
   *          (required)
   * @param pTime
   *          (required)
   * @param locationid (required)
   * @return
   */
  @POST
  @RequireUserRole(roles = User.USER_ROLE.USER)
  public Response createEvent(@FormParam("name") String pName,
      @FormParam("description") String pDescription,
      @FormParam("categoryid") String pCategoryID,
      @FormParam("time") long pTime,
      @FormParam("locationid") String pLocationID,
      @Context SecurityContext pSecurityContext) {
    LOG.debug("createEvent(name={}, description={}, categoryId={}, time={})",
        pName, pDescription, pCategoryID, pTime);
    try {
      Event event = new Event();
      event.setName(pName);
      event.setDescription(pDescription);
      event.setContact(getUserFromSecurityContext(pSecurityContext));
      event.setResponsible(getUserFromSecurityContext(pSecurityContext));
      event.setCategory(getCategory(pCategoryID));
      event.setStatus(Event.EVENTSTATUS.ACTIVE);
      event.setTime(new Date(pTime));
      event.setLocation(getLocationData().getLocation(pLocationID));

      if (!event.isValid()) {
        return getBadRequestResponse();
      }
      event = getEventData().createEvent(event);
      return getCreatedResponse("/id/" + event.getId());
    } catch (DatabaseException dbe) {
      return getBadRequestResponse(dbe);
    }
  }

  private EventCategory getCategory(String pCategoryID)
      throws DatabaseException {
    return getEventCategoryData().getEventCategory(pCategoryID);
  }

  @Override
  protected Logger getLogger() {
    return LOG;
  }
}
